$(function() {
    //从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    const user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if(user == null || token == null){
        alert("请先登录");
        window.location.href = "../html/welcome.html";
    }

    //初始化用户信息
    const url = window.location.href;
    if(url.split("?").length > 1){
        const username = decodeURIComponent(url.split("?")[1].split("&")[0].split("=")[1]);
        const email = decodeURIComponent(url.split("?")[1].split("&")[1].split("=")[1]);
        $("#username").html(username);
        $("#email").html(email);
    }

    //初始化时的第一次请求 渲染第一页初次审核的吐槽数据
    pageAjax(token,1);
    //初始化时的第一次请求 渲染第一页二次审核的吐槽数据
    againPageAjax(token,1);

    //为底部分页框添加分页方法 初次审核
    $("#pageSelect").change(function(){
        pageAjax(token,$(this).children('option:selected').val());
    })
    //为底部分页框添加分页方法 二次审核
    $("#againPageSelect").change(function(){
        againPageAjax(token,$(this).children('option:selected').val());
    })

    //为审核按钮添加点击事件
    for (let i = 1; i <= 10; i++) {
        //初次审核
        $("#verifyBtn" + i).click(function (){
            const tucaoId = $("#num" + i).text();
            getTucaoByIdAjax(token,tucaoId);
        });
        //二次审核
        $("#againVerifyBtn" + i).click(function (){
            const tucaoId = $("#againNum" + i).text();
            getTucaoByIdAjax(token,tucaoId);
        });
    }

    //为审核通过和审核未通过按钮添加点击事件
    $("#verifyTrueBtn").click(function (){
        const tucaoId = $("#sTucaoId").text();
        verifyTucaoAjax(token,tucaoId,"true");
    });
    $("#verifyFalseBtn").click(function (){
        const tucaoId = $("#sTucaoId").text();
        verifyTucaoAjax(token,tucaoId,"false");
    });

    //给退出登录按钮添加点击事件
    $("#logoutBtn").click(function (){
        logoutAjax(user.username);
        window.setTimeout(function(){
            window.location.href = "../html/welcome.html";
        },2000);
    });

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url :"http://localhost:2082/logout?username=" + user.username
        })
    });

});

//未审核吐槽数据分页ajax
function pageAjax(token,current) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/tucao/page?verify=0&current=" + current,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if(token == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("("+JSON.stringify(pageData)+")").records;
                    //total：所有数据的数量
                    const total = eval("("+JSON.stringify(pageData)+")").total;
                    //size：每页数据的数量
                    const size = eval("("+JSON.stringify(pageData)+")").size;
                    //current：当前页数
                    const current = eval("("+JSON.stringify(pageData)+")").current;
                    //总页数
                    const pageNum = eval("("+JSON.stringify(pageData)+")").pages;

                    //初始化底部分页框
                    $("#totalPage").empty();
                    $("#totalPage").html(pageNum);
                    $("#pageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        const pageValue = i + 1;
                        if(current === pageValue){
                            $("#pageSelect").append("<option value='"+pageValue+"' selected>"+pageValue+"</option>");
                        }else {
                            $("#pageSelect").append("<option value='"+pageValue+"'>"+pageValue+"</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 10; i++) {
                        $("#num" + i).empty();
                        $("#tucaoSort" + i).empty();
                        $("#tucaoAuthor" + i).empty();
                    }
                    //再进行赋值
                    let tucaoNum;
                    if( (total-size*(current-1)) >= 10){
                        tucaoNum = 10;
                    }else if( (total-size*(current-1)) < 10){
                        tucaoNum = total-size*(current-1);
                        for (let i = tucaoNum + 1; i <= 10; i++) {
                            //添加不可见样式
                            $("#row" + i).attr("style","display:none");
                        }
                    }
                    for (let i = 1; i <= tucaoNum; i++) {
                        //移除不可见样式
                        $("#row" + i).removeAttr("style");
                        let tucaoId = JSON.stringify(records[i-1].tucaoId);
                        let sort = JSON.stringify(records[i-1].sort);
                        let username = JSON.stringify(records[i-1].username);
                        if(tucaoId == null){
                            tucaoId = "/";
                        }
                        if(sort == null){
                            sort = "/";
                        }
                        if(username == null){
                            username = "/";
                        }
                        $("#num" + i).html(tucaoId.replace(/\"/g, ""));
                        $("#tucaoSort" + i).html(sort.replace(/\"/g, ""));
                        $("#tucaoAuthor" + i).html(username.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    $('#add').modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//已审核吐槽数据分页ajax
function againPageAjax(token,current) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/tucao/page?current=" + current +"&getVerified=true",
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if(token == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("("+JSON.stringify(pageData)+")").records;
                    //total：所有数据的数量
                    const total = eval("("+JSON.stringify(pageData)+")").total;
                    //size：每页数据的数量
                    const size = eval("("+JSON.stringify(pageData)+")").size;
                    //current：当前页数
                    const current = eval("("+JSON.stringify(pageData)+")").current;
                    //总页数
                    const pageNum = eval("("+JSON.stringify(pageData)+")").pages;

                    //初始化底部分页框
                    $("#againTotalPage").empty();
                    $("#againTotalPage").html(pageNum);
                    $("#againPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        let pageValue = i + 1;
                        if(current === pageValue){
                            $("#againPageSelect").append("<option value='"+pageValue+"' selected>"+pageValue+"</option>");
                        }else {
                            $("#againPageSelect").append("<option value='"+pageValue+"'>"+pageValue+"</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 10; i++) {
                        $("#againNum" + i).empty();
                        $("#againTucaoSort" + i).empty();
                        $("#againTucaoAuthor" + i).empty();
                        $("#againVerifyResult" + i).empty();
                    }
                    //再进行赋值
                    let againTucaoNum;
                    if( (total-size*(current-1)) >= 10){
                        againTucaoNum = 10;
                    }else if( (total-size*(current-1)) < 10){
                        againTucaoNum = total-size*(current-1);
                        for (let i = againTucaoNum + 1; i <= 10; i++) {
                            //添加不可见样式
                            $("#againRow" + i).attr("style","display:none");
                        }
                    }
                    for (let i = 1; i <= againTucaoNum; i++) {
                        //移除不可见样式
                        $("#againRow" + i).removeAttr("style");
                        let tucaoId = JSON.stringify(records[i-1].tucaoId);
                        let sort = JSON.stringify(records[i-1].sort);
                        let username = JSON.stringify(records[i-1].username);
                        let verify = JSON.stringify(records[i-1].verify);
                        if(tucaoId == null){
                            tucaoId = "/";
                        }
                        if(sort == null){
                            sort = "/";
                        }
                        if(username == null){
                            username = "/";
                        }
                        if(verify == null){
                            verify = "/";
                        }else if(verify == 1){
                            verify = "通过";
                        }else if(verify == 2){
                            verify = "未通过";
                        }
                        $("#againNum" + i).html(tucaoId.replace(/\"/g, ""));
                        $("#againTucaoSort" + i).html(sort.replace(/\"/g, ""));
                        $("#againTucaoAuthor" + i).html(username.replace(/\"/g, ""));
                        $("#againVerifyResult" + i).html(verify.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    $('#add').modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//获取其中一条吐槽数据ajax
function getTucaoByIdAjax(token,tucaoId){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/tucao/one?tucaoId=" + tucaoId,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if(token == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const tucaoData = result.data;
                    const username = eval("("+JSON.stringify(tucaoData)+")").username;
                    const sort = eval("("+JSON.stringify(tucaoData)+")").sort;
                    const createTime = eval("("+JSON.stringify(tucaoData)+")").createTime;
                    const place = eval("("+JSON.stringify(tucaoData)+")").place;
                    const tucaoId = eval("("+JSON.stringify(tucaoData)+")").tucaoId;
                    const content = eval("("+JSON.stringify(tucaoData)+")").content;

                    //先清空数据
                    $("#sUsername").empty();
                    $("#sSort").empty();
                    $("#sTime").empty();
                    $("#sPlace").empty();
                    $("#sTucaoId").empty();
                    $("#sContent").empty();
                    //再进行赋值
                    $("#sUsername").html(username);
                    $("#sSort").html(sort);
                    $("#sTime").html(createTime);
                    $("#sPlace").html(place);
                    $("#sTucaoId").html(tucaoId);
                    $("#sContent").html(content);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//对一条吐槽进行审核ajax
function verifyTucaoAjax(token,tucaoId,verify){
    $.ajax({
        type: "PUT",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/tucao/verify?tucaoId=" + tucaoId +"&verify=" + verify,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                if(result.code == 200){
                    $("#changeSource").modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再进行一次分页显示操作
                    const current = $("#pageSelect option:selected").text();
                    pageAjax(token,current);
                    const againCurrent = $("#againPageSelect option:selected").text();
                    againPageAjax(token,againCurrent);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//退出登录
function logoutAjax(username) {
    $.ajax({
        type:"POST",
        contentType:"application/json",
        url :"http://localhost:2082/logout?username=" + username,
        success : function(data) {
            let result = JSON.stringify(data);
            result = eval("("+result+")");
            //操作成功
            if(result.code == 200){
                spop({
                    template: "管理员退出成功",
                    position  : 'top-center',
                    group: "submit-satus",
                    style: "success",
                    autoclose: 2000
                });
            }
            //操作失败
            if(result.code == 500){
                $('#register').modal('hide');
                spop({
                    template: result.msg,
                    position  : 'top-center',
                    group: "submit-satus",
                    style: "fail",
                    autoclose: 2000
                });
            }
        }
    })
}












